<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-29 20:04:48
 * @Description  : 登录日志管理
-->
<template>
  <div class="bg-lightColor loginLog-con p-3 rounded">
    <n-grid x-gap="12" :cols="1" class="mb-2">
      <n-gi class="flex">
        <time-select @time-change="handleTimeChange"></time-select>
        <UserSelect
          class="!w-[300px] ml-2"
          :multiple="false"
          @change-value="handleUserChange"
        ></UserSelect>
        <n-button
          class="ml-4"
          size="small"
          @click="exportSorterAndFilterCsv"
          type="tertiary"
        >
          导出
        </n-button>
      </n-gi>
    </n-grid>
    <wp-data-table
      v-loading="loading"
      :data="data"
      :checked-row-keys="checkedRowKeys"
      :columns="columns"
      :pages="pageResultInfo.pages"
      :total="pageResultInfo.total"
      @page-change="handlePageChange"
      @select-change="handleSelectChange"
      @sort-change="handleSorterChange"
      ref="loginLogTableRef"
      :is-sort="false"
    >
    </wp-data-table>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import type { DataTableColumns } from 'naive-ui'
import useUserStore from '@/stores/modules/user'
import { getLogByPage } from '@/api/log'
import type { LogReq, LogRowData } from '@/types/log'
import { formatTime } from '@/utils/index'
import {
  renderIp,
  renderLogExport,
  renderOs,
  renderUserAvator
} from '@/utils/commonBusiness'
import { getStartAndEndTime } from '@/utils/index'
import DisableUserPic from '@/assets/images/default-avata-disable.jpg'
import WpDataTable from '@/components/WpDataTable/index.vue'
import TimeSelect from '../components/TimeSelect.vue'
import type { IndexObj } from '@/types/commom'

const userStore = useUserStore()

const data = ref<LogRowData[]>([])
const pageInfo = reactive<LogReq>({
  page: 1,
  pageSize: 50,
  type: 'user.login',
  userId: undefined,
  startTime:
    getStartAndEndTime(0).startTime!.format('YYYY-MM-DD HH:mm:ss') || undefined,
  endTime:
    getStartAndEndTime(0).endTime.format('YYYY-MM-DD HH:mm:ss') || undefined
})

const handleTimeChange = (time: IndexObj) => {
  pageInfo.startTime = time.startTime
  pageInfo.endTime = time.endTime
  loadLoginLogs()
}

const handleUserChange = (value: string | string[]) => {
  if (value === '') {
    pageInfo.userId = undefined
  } else {
    pageInfo.userId = value as string
  }
  loadLoginLogs()
}

const pageResultInfo = reactive({
  pages: 0,
  total: 0
})
const loading = ref(false)

const createColumns = (): DataTableColumns<LogRowData> => {
  return [
    {
      title: '用户',
      key: 'userInfo',
      width: 150,
      minWidth: 150,
      render: (row) => {
        if (!row.user) {
          return renderUserAvator(DisableUserPic, '已删除')
        }
        const curUsername =
          userStore.userInfo?.id === row.user?.id
            ? '我自己'
            : row.user?.username
        return renderUserAvator(
          row.user?.avator as string,
          curUsername as string
        )
      }
    },
    {
      title: '登录时间',
      key: 'createTime',
      sorter: 'default',
      width: 150,
      minWidth: 150,
      render(row) {
        return formatTime(row.createTime)
      }
    },
    {
      title: '系统',
      key: 'os',
      width: 150,
      minWidth: 150,
      render(row) {
        return renderOs(row.uaParse.os)
      }
    },
    {
      title: '客户端',
      key: 'browser',
      width: 150,
      minWidth: 150,
      render(row) {
        return renderOs(row.uaParse.browser)
      }
    },
    {
      title: '登录地址',
      key: 'ip',
      width: 150,
      minWidth: 150,
      render(row) {
        return renderIp(row.ip)
      }
    }
  ]
}

// 创建时间那一列的sort筛选排序发生变化
const handleSorterChange = (sorter: IndexObj) => {
  if (sorter && sorter.columnKey === 'createTime') {
    if (sorter.order === 'ascend') {
      data.value = data.value.sort((v1: LogRowData, v2: LogRowData) => {
        return dayjs(v1.createTime).valueOf() - dayjs(v2.createTime).valueOf()
      })
    } else {
      data.value = data.value.sort((v1: LogRowData, v2: LogRowData) => {
        return dayjs(v2.createTime).valueOf() - dayjs(v1.createTime).valueOf()
      })
    }
  }
}

const checkedRowKeys = ref<string[]>([])

const columns = createColumns()

const loginLogTableRef = ref<any>()

// 导出日志
const exportSorterAndFilterCsv = () =>
  loginLogTableRef.value!.tableRef!.downloadCsv({
    fileName: 'login-logs-' + dayjs().format('YYYY-MM-DD HH:mm:ss'),
    keepOriginalData: true
  })

// 获取登录日志列表
const loadLoginLogs = () => {
  loading.value = true
  getLogByPage(pageInfo)
    .then((res) => {
      res.data.items.forEach((item) => {
        renderLogExport(item)
      })
      data.value = res.data.items
      pageResultInfo.pages = res.data.pages
      pageResultInfo.total = res.data.total
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  loadLoginLogs()
})

const handlePageChange = (page?: number, pageSize?: number) => {
  page && (pageInfo.page = page)
  pageSize && (pageInfo.pageSize = pageSize)
  loadLoginLogs()
}

const handleSelectChange = (rows: string[]) => {
  checkedRowKeys.value = rows.map((item) => item)
}
</script>

<style scoped lang="scss">
.loginLog-con {
  font-size: 13px;

  :deep(.n-data-table-tbody .n-data-table-tr:hover .n-data-table-td) {
    background-color: #e5f3ff;
  }
}
</style>
